# -*- coding: utf-8 -*-

import yaml
import logging

log = logging.getLogger('yscripts')

CONFIG_FILE_PATH = 'vmtokubevirt_generator.yml'
TEMPLATE_DIR = ''
TEMPLATE_VM_PATH = 'template_vm.yml'
TEMPLATE_DISK_PATH = 'template_disk.yml'

class VirtualMachine(object):
    def __init__(self):
        self.conf = {}
        pass

    def get_config(self):
        with open(CONFIG_FILE_PATH, 'r', encoding='utf-8') as f:
            conf = yaml.safe_load(f)

        self.conf = conf

    def _generate_disks(self):
        if len(self.conf['volumes']) == 0:
            log.error("没有找到磁盘信息！")
            print("没有找到磁盘信息")
            return

        with open(TEMPLATE_DISK_PATH, 'r') as f:
            templ = yaml.safe_load(f)

        for disk in self.conf['volumes']:
            disk_name = '-'.join([self.conf['name'], disk['id']])
            templ['metadata']['name'] = disk_name
            templ['metadata']['namespace'] = self.conf['namespace']
            templ['metadata']['labels']['sys.99bill.com/user'] = self.conf['owner']['name']
            templ['metadata']['labels']['sys.99bill.com/user-group'] = self.conf['owner']['group']
            templ['metadata']['annotations']['dev.99bill.com/vm'] = self.conf['name']
            templ['metadata']['annotations']['dev.99bill.com/email'] = self.conf['owner']['email']
            templ['metadata']['annotations']['dev.99bill.com/os'] = self.conf['os']['version']
            templ['metadata']['annotations']['dev.99bill.com/description'] = self.conf['description']
            templ['spec']['source']['vddk']['backingFile'] = disk['backingFile']
            templ['spec']['source']['vddk']['uuid'] = self.conf['uuid']
            templ['spec']['storage']['resources']['requests']['storage'] = disk['storage']

            with open(disk_name + '.yml', 'w', encoding='utf-8') as fw:
                yaml.safe_dump(templ, fw, default_flow_style=False, encoding='utf-8', allow_unicode=True)
                log.info("输入磁盘文件%s", disk_name)

    def _generator_vm(self):
        with open(TEMPLATE_VM_PATH, 'r') as f:
            templ = yaml.safe_load(f)

        templ['metadata']['name'] = self.conf['name']
        templ['metadata']['namespace'] = self.conf['namespace']
        templ['metadata']['labels']['kubevirt.io/os'] = self.conf['os']['version']
        templ['spec']['template']['metadata']['labels']['kubevirt.io/os'] = self.conf['os']['version']
        templ['spec']['template']['metadata']['annotations']['ovn.kubernetes.io/logical_switch'] = self.conf['switch']
        templ['spec']['template']['metadata']['annotations']['ovn.kubernetes.io/ip_address'] = self.conf['ip4']
        templ['spec']['template']['metadata']['annotations']['ovn.kubernetes.io/mac_address'] = self.conf['mac']
        templ['spec']['template']['metadata']['annotations']['hci.99bill.com/owner-name'] = self.conf['owner']['name']
        templ['spec']['template']['metadata']['annotations']['hci.99bill.com/owner-group'] = self.conf['owner']['group']
        templ['spec']['template']['metadata']['annotations']['hci.99bill.com/owner-email'] = self.conf['owner']['email']
        templ['spec']['template']['metadata']['annotations']['hci.99bill.com/os'] = self.conf['os']['version']
        templ['spec']['template']['metadata']['annotations']['hci.99bill.com/description'] = self.conf['description']
        templ['spec']['template']['spec']['domain']['cpu']['cores'] = self.conf['os']['cpu']
        templ['spec']['template']['spec']['domain']['memory']['guest'] = self.conf['os']['mem']
        templ['spec']['template']['spec']['domain']['resources']['limits']['cpu'] = self.conf['os']['cpu']
        templ['spec']['template']['spec']['domain']['resources']['limits']['memory'] = self.conf['os']['mem']

        vs = templ['spec']['template']['spec']['volumes']
        ds = templ['spec']['template']['spec']['domain']['devices']['disks']
        for disk in self.conf['volumes']:
            disk_name = '-'.join([self.conf['name'], disk['id']])
            vs.append({'persistentVolumeClaim': {'claimName': disk_name}, 'name': disk['id']})
            ds.append({'name': disk['id'], 'disk': {'bus': 'virtio'}})

        with open(self.conf['name'] + '.yml', 'w', encoding='utf-8') as fw:
            yaml.safe_dump(templ, fw, default_flow_style=False, encoding='utf-8', allow_unicode=True)
            log.info("输入虚拟机文件%s", disk_name)

    def generator(self):
        self._generate_disks()
        self._generator_vm()

if __name__ == '__main__':
    print("Starting...")
    vm = VirtualMachine()
    vm.get_config()
    vm.generator()